package br.uniceub.fsw.agenda.controller;

import br.uniceub.fsw.agenda.exception.BusinessException;
import br.uniceub.fsw.agenda.exception.DatabaseException;
import br.uniceub.fsw.agenda.model.vo.UsuarioVO;
import br.uniceub.fsw.agenda.model.facade.ManterUsuarioFacade;
import java.io.*;
import java.net.*;

import javax.servlet.*;
import javax.servlet.http.*;

/**
 * 06/04/2008
 * @author Rodrigo Uchôa - rodrigo.uchoa@yahoo.com
 */
public class LoginController extends GenericServlet {
    private String nomeTela = "/login.jsp";
    private String nomeCasoDeUsoPadrao = "/ControllerConsultarPessoa?method=iniciarTela";

    public void iniciarTela(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        RequestDispatcher rd = request.getRequestDispatcher(nomeTela);
        rd.forward(request, response);
        
    }

    public void fazerLogin(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //parametros da tela
        String login = request.getParameter("dsLogin");
        String senha = request.getParameter("dsSenha");
        
        //Facades
        ManterUsuarioFacade facadeUsuario = new ManterUsuarioFacade();        
        try {
            UsuarioVO usuario = facadeUsuario.fazerLogin(login, senha);
            
            request.getSession().setAttribute("SESSION_USER", usuario);
            
            RequestDispatcher rd = request.getRequestDispatcher(nomeCasoDeUsoPadrao);
            rd.forward(request, response);
            
        } catch (BusinessException ex) {
            request.setAttribute("mensagem", ex.getMessage());            
            RequestDispatcher rd = request.getRequestDispatcher(nomeTela);
            rd.forward(request, response);
        } catch (DatabaseException ex) {  
            request.setAttribute("mensagem", "Erro de comunicação com o banco de dados.");            
            RequestDispatcher rd = request.getRequestDispatcher(nomeTela);
            rd.forward(request, response);
        }
    }
   
    
}
